/*
 * 主程序v0.1 使用这个启动整个bot
 * 很爛的java代碼... 
 * @author @bonex2
 */
package main;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.Vector;

public class MainProc extends Thread {

	void logError(int errorType) {
		System.err.println("No connection now!");
	}

	/**
	 * 根據type和subtype獲取指定的句子
	 * 
	 * @param conn
	 * @param type
	 * @param subtype
	 * @return
	 */
	SentencePair getSentenceByType2(Connection conn, long type, long subtype) {
		SentencePair sentence = new SentencePair();
		if (conn == null) {
			logError(-1);
		} else {
			try {
				String baseSql = "SELECT A.ID, A.DETAIL FROM SENTENCES A WHERE TYPE = ? AND SUBTYPE = ? AND (LAST_TWEETED IS NULL OR (TO_DAYS(NOW()) - TO_DAYS(LAST_TWEETED)) >= 1)";
				PreparedStatement stmt = conn.prepareStatement(baseSql);
				stmt.setLong(1, type);
				stmt.setLong(2, subtype);
				ResultSet rs = stmt.executeQuery();
				sentence = getRandomSentence(rs);
			} catch (Exception e) {
				System.err.println(e);
			}
		}
		return sentence;
	}

	/**
	 * 從ResultSet中隨機獲取可用的句子
	 * 
	 * @param rs
	 * @return
	 */
	static SentencePair getRandomSentence(ResultSet rs) {
		SentencePair returnValue = new SentencePair();
		Vector vs = new Vector();
		try {
			while (rs.next()) {
				SentencePair sentence = new SentencePair();
				sentence.setId(rs.getLong("ID"));
				sentence.setSentence(rs.getString("DETAIL"));
				vs.add(sentence);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (vs.size() > 0) {
			// 優化random代碼,不再开根号
			Random r = new Random();
			// r.setSeed((long)Math.sqrt((double)System.currentTimeMillis()));
			double percent = r.nextDouble();
			int v = (int) (percent * (double) vs.size());
			if (v < vs.size()) {
				returnValue = (SentencePair) vs.elementAt(v);
			} else {
				returnValue = (SentencePair) vs.elementAt(0);
			}
		}
		return returnValue;
	}

	/**
	 * 自動取新句(報時和測試除外)
	 * 
	 * @param conn
	 * @return
	 */
	SentencePair getSentence(Connection conn) {
		SentencePair sentence = new SentencePair();
		if (conn == null) {
			logError(-1);
		} else {
			try {
				String baseSql = "SELECT A.ID, A.DETAIL FROM SENTENCES A WHERE NOT TYPE = 11 AND NOT TYPE = 1 AND (LAST_TWEETED IS NULL OR (TO_DAYS(NOW()) - TO_DAYS(LAST_TWEETED)) >= 1)";
				PreparedStatement stmt = conn.prepareStatement(baseSql);
				ResultSet rs = stmt.executeQuery();
				sentence = getRandomSentence(rs);
			} catch (Exception e) {
				System.err.println(e);
			}
		}
		return sentence;
	}

	/**
	 * 根據type獲取句子
	 * 
	 * @param conn
	 * @param type
	 * @return
	 */
	SentencePair getSentenceByType(Connection conn, long type) {
		SentencePair sentence = new SentencePair();
		if (conn == null) {
			logError(-1);
		} else {
			try {
				String baseSql = "SELECT A.ID, A.DETAIL FROM SENTENCES A WHERE TYPE = ? AND (LAST_TWEETED IS NULL OR (TO_DAYS(NOW()) - TO_DAYS(LAST_TWEETED)) >= 1)";
				PreparedStatement stmt = conn.prepareStatement(baseSql);
				stmt.setLong(1, type);
				ResultSet rs = stmt.executeQuery();
				sentence = getRandomSentence(rs);
			} catch (Exception e) {
				System.err.println(e);
			}
		}
		return sentence;
	}

	/**
	 * 主循环
	 */
	public void run() {
		while (true) {

			try {
				Connection conn = new Dao().getConn();
				Date currDate = new Date();
				// 时间subtype的格式,以100开头.時間類型ID
				SimpleDateFormat df = new SimpleDateFormat("100HHmmss");
				// 正点报时
				if ((currDate.getMinutes() == 0 && currDate.getSeconds() == 0)
						|| df.format(currDate).equals("100111111")) {
					System.out.println(df.format(currDate));
					SentencePair sentence = getSentenceByType2(conn, 1, Long
							.parseLong(df.format(currDate)));
					if (sentence.isNull()) {
						// 2010-2-23 23:36 修改Log方式
						// System.out.println(System.currentTimeMillis()
						// + ":我无话可说了!I've no word to say!");
						SentencePair systemLog = new SentencePair(
								Common.DEFAULT_TIME_YMDHMS.format(currDate)
										+ ":我无话可说了1!I've no word to say1!");
						Action2Log.insertLog(systemLog, null, systemLog
								.getSentence());
						// 2010-2-23 23:36 end
						Thread.sleep(1000);
						continue;
					}
					// 2010-2-20 1:47 新方法替代老的发推方式
					else {
						// 2010-2-23 23:29追加 统计过去一天调戏的人
						if (df.format(currDate).equals("100000000")) {
							int tweeted = Utils.getSaid(conn);
							int userCount = Utils.getMentionedUserCount(conn);
							UserLite mentionedUser = Utils
									.getMentionedUser(conn);
							SentencePair systemLog = new SentencePair(
									"在过去的一天里，我一共发言"
											+ tweeted
											+ "次。调戏"
											+ userCount
											+ "个bot/人，最后一次调戏的是"
											+ Common.USER_TAG
											+ mentionedUser.getScreenName()
											+ "酱。嗯，今天我也不会辜负主人的期望，尽最大努力调戏大家的！哎嘿=w=");
							Utils.tweetATweet(systemLog);
						}
						// 2010-2-23 23:29 end
						Utils.tweetATweet(sentence);
					}
					// Twitter twitter = new TwitterFactory("").getInstance(
					// // 2010-2-18 23:14 修正用戶密碼
					// Common.USER, Common.PASSWORD);
					// // 2010-2-18 23:14 end
					// Status status = twitter.updateStatus(sp.getSentence());
					// if (status != null && status.getId() > 0) {
					// updateTweetedTime(conn, sp, status.getCreatedAt());
					// }
					// System.out.println("Now is on O'clock!");
					// 2010-2-20 1:47 end
				} else if (currDate.getSeconds() == 0) {
					System.out.println(Common.DEFAULT_TIME_YMDHMS
							.format(currDate));
				} else {
					// 優化random代碼
					Random r = new Random();
					// r.setSeed(currDate.getTime());
					double d = r.nextDouble();
					if (d > 0.9992) {
						SentencePair sentence = getSentence(conn);
						if (sentence.isNull()) {
							// 2010-2-23 23:36 修改Log方式
							// System.out.println(System.currentTimeMillis()
							// + ":我无话可说了!I've no word to say!");
							SentencePair systemLog = new SentencePair(
									Common.DEFAULT_TIME_YMDHMS.format(currDate)
											+ ":我无话可说了1!I've no word to say1!");
							Action2Log.insertLog(systemLog, null, systemLog
									.getSentence());
							// 2010-2-23 23:36 end

							Thread.sleep(1000);
							continue;
						}
						// 2010-2-20 1:47 新方法替代老的发推方式
						else {
							Utils.tweetATweet(sentence);
						}
						// Twitter twitter = new TwitterFactory("")
						// .getInstance(Common.USER/* 用戶名 */,
						// Common.PASSWORD /* 密碼 */);
						// Status status =
						// twitter.updateStatus(sp.getSentence());
						// if (status != null && status.getId() > 0) {
						// updateTweetedTime(conn, sp, status.getCreatedAt());
						// }
						// 2010-2-20 1:47 end
					}
				}
				conn.close();
				Thread.sleep(1000);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * test
	 * 
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		new MainProc().start();
		new Utils().start();
	}

}
